package com.shuigu.security;

import com.shuigu.pojo.entity.UmsMenu;
import com.shuigu.service.IUmsMenuService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.function.Supplier;

/**
 *  动态权限控制
 *  判断请求路径是否有权限访问
 */
@Component
@Slf4j
public class MyAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Resource
    private IUmsMenuService menuService;

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext requestAuthorizationContext) {
        //获取请求路径，获取HttpServletRequest
        HttpServletRequest request = requestAuthorizationContext.getRequest();
        String uri = request.getRequestURI();
        String url = request.getRequestURL().toString();
        log.info("uri============{}", uri);
        log.info("url============{}", url);
        //有些请求不需要认证
        if("/auth/sys".equals(uri) || "/error".equals(uri) || "/ums/role/self".equals(uri)) {
            return new AuthorizationDecision(true);
        }
        //根据uri获取路径的权限permissionRepository.getPermissionByPath(uri);
        UmsMenu menu = menuService.lambdaQuery().eq(UmsMenu::getComponentPath, uri).one();
        if(menu == null ){
            return new AuthorizationDecision(false);
        }
        //获取路径访问权限
        String perm = menu.getPerms();
        log.info("路径权限============{}",perm);
        if(perm == null || perm.trim().isEmpty()){
            return new AuthorizationDecision(true);
        }

        //与用户的权限集合做判断
        Collection<? extends GrantedAuthority> authorities = authentication.get().getAuthorities();
        for (GrantedAuthority authority : authorities) {
            String userPerm = authority.getAuthority();
            log.info("用户权限========{}",userPerm);
            if(userPerm.equals(perm)){
                return new AuthorizationDecision(true);
            }
        }
        return new AuthorizationDecision(false);
    }
}
